//
//  ReportViewController.m
//  MClient
//
//  Created by  史正烨 on 09-11-22.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ReportViewController.h"
#import "MServerJsonDAO.h"
#import "MCFunction.h"
#import "MClientAppDelegate.h"
#import "QueryController.h"

@interface ReportViewController (Private)
- (NSString *)getReportUrl; 
@end

@implementation ReportViewController
@synthesize reportDefId;
@synthesize initialValues;
@synthesize presentType;

- (id)init {
	if (self = [super init]) {
		self.hidesBottomBarWhenPushed = YES;
	}
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter07.html";
}

- (void)dealloc {
	[reportDefId release];
	[initialValues release];
	[presentType release];
    [super dealloc];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {
	NSString *url = [[self getReportUrl] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
	NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:[MServerJsonDAO getCookies]];
	[request setAllHTTPHeaderFields:headers];
	[self.webView loadRequest:request];
}

#pragma mark ---- 内部方法 ----
- (NSString *)getReportUrl {
	NSString *serverUrl = [self.userDefaults.current_ServerUrl retain];
	serverUrl = [serverUrl stringByAppendingFormat:@"/beapp/AppPageServlet?__action=forward_report&__report_def_id=%@",self.reportDefId];
	if (self.presentType != nil) {
		serverUrl = [serverUrl stringByAppendingFormat:@"&__present_type=%@",self.presentType];
	}

	for(NSMutableDictionary *filter in self.initialValues) {
		NSString *name = [filter objectForKey:@"fld"];
		NSString *value = [filter objectForKey:@"value"];
		NSString *type = [filter objectForKey:@"type"];
		if ([filter objectForKey:@"rfld"]) {
			name = [name stringByAppendingString:[filter objectForKey:@"rfld"]];
		}
		name = [[MCFunction getQueryName:name queryMode:type] retain];
		serverUrl = [serverUrl stringByAppendingFormat:@"&%@=%@",name,value];
	}
	MCLog(@"loadUrl = %@", serverUrl);
	return serverUrl;
}

- (void) selectCancelAction: (id) sender {
	UIViewController *viewController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
	if ([viewController isMemberOfClass:[QueryController class]]){
		[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 3] animated:YES];
		return;
	}
	[self.navigationController popViewControllerAnimated:YES];
}

@end
